//
//  HOConfirmOrderViewController.m
//  微度报修
//
//  Created by foguo-mac-1 on 6/26/16.
//  Copyright © 2016 WeiDu. All rights reserved.
//

#import "HOConfirmOrderViewController.h"
#import "HOConstants.h"
#import "HOEditView.h"
#import "RatingBar.h"
#import "HOUtils.h"
#import "HORepairerEntity.h"
#import "UIImageView+WebCache.h"

@interface HOConfirmOrderViewController ()<HOEditViewDelegate>
{
	HOEditView *commentsEditView;
	BOOL		isNeedRepair;
	RatingBar	*ratingBarView;
	HORepairerEntity *repairerEntity;
}
@end

@implementation HOConfirmOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
	[self initTableView];
	[self registerTapGesture];
	[self initSubviews];
	[self registerKeyboard];
	repairerEntity = [[HORepairerEntity alloc] init];
	[self requestData];
	
}

- (void)requestData
{
	[self sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_GetRepairmanInfo,
								  kHO_FIELD_UserId:[NSNumber numberWithInt:self.orderEntity.doneId]}];
}

- (void)initSubviews
{
	commentsEditView = [[HOEditView alloc] initWithFrame:CGRectMake(0,
																	  0,
																	  self.view.frame.size.width,
																	  134)];
	commentsEditView.limitedCount = 120;
	commentsEditView.delegate = self;
	commentsEditView.layer.cornerRadius = 0;
	commentsEditView.layer.borderWidth = 0;
	[commentsEditView.layer setMasksToBounds:YES];
	[commentsEditView setPlaceHolder:NSLocalizedString(@"说点什么", @"说点什么")];
	[commentsEditView getTextView].returnKeyType = UIReturnKeySend;
	
	ratingBarView = [[RatingBar alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 90) / 2,
																		75,
																		90,
																		30)
										  withHighlightImage:@"icon_solidstar_yellow_lg"
											 withNormalImage:@"icon_solidstar_gray_lg"];
	
	
	baseTableview.tableFooterView = [self getFooterView];
}

- (UIView *)getFooterView
{
	UIView *view = [[[UIView alloc]initWithFrame:CGRectMake(0,
															0,
															baseTableview.frame.size.width,
															110)] autorelease];
	UIButton *uncompleteBtn = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
	uncompleteBtn.frame = CGRectMake(HO_HORIZONAL_PADDING,
								 IS_IPHONE_4_SCREEN ? 5 : HO_HORIZONAL_PADDING,
								 baseTableview.frame.size.width / 2 - 3 * HO_HORIZONAL_PADDING,
								 40);
	[uncompleteBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
	[uncompleteBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
	[uncompleteBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
	[uncompleteBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
	[uncompleteBtn setTintColor:[UIColor whiteColor]];
	[uncompleteBtn setTitle:NSLocalizedString(@"未完成", @"未完成") forState:UIControlStateNormal];
	[uncompleteBtn addTarget:self action:@selector(uncompleteFault:) forControlEvents:UIControlEventTouchUpInside];
	[uncompleteBtn setBackgroundImage:[HOUtils createImageWithColor:UIColorFromRGB(0xc11a1a) forView:uncompleteBtn] forState:UIControlStateNormal];
//	[uncompleteBtn setBackgroundImage:[HOUtils createImageWithColor:TEXT_GRAY_DARK_dbdbdb forView:uncompleteBtn] forState:UIControlStateDisabled];
	uncompleteBtn.titleLabel.font = [UIFont systemFontOfSize:15];
	[uncompleteBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
	uncompleteBtn.layer.cornerRadius = 3;
	[uncompleteBtn.layer setMasksToBounds:YES];
	[view addSubview:uncompleteBtn];
	
	UIButton *footerBtn = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
	footerBtn.frame = CGRectMake(baseTableview.frame.size.width / 2  + HO_HORIZONAL_PADDING,
								 IS_IPHONE_4_SCREEN ? 5 : HO_HORIZONAL_PADDING,
								 baseTableview.frame.size.width / 2 - 3 * HO_HORIZONAL_PADDING,
								 40);
	[footerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
	[footerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
	[footerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
	[footerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
	[footerBtn setTintColor:[UIColor whiteColor]];
	[footerBtn setTitle:NSLocalizedString(@"确认完成(评价)", @"确认完成(评价)") forState:UIControlStateNormal];
	[footerBtn addTarget:self action:@selector(didClickFooterButton:) forControlEvents:UIControlEventTouchUpInside];
	[footerBtn setBackgroundImage:[HOUtils createImageWithColor:MAIN_COLOR_NORMAL forView:footerBtn] forState:UIControlStateNormal];
	[footerBtn setBackgroundImage:[HOUtils createImageWithColor:TEXT_GRAY_DARK_dbdbdb forView:footerBtn] forState:UIControlStateDisabled];
	footerBtn.titleLabel.font = [UIFont systemFontOfSize:15];
	[footerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
	footerBtn.layer.cornerRadius = 3;
	footerBtn.tag = 111;
	[footerBtn.layer setMasksToBounds:YES];
	[view addSubview:footerBtn];
	
	return view;
}

- (void)uncompleteFault:(UIButton *)sender
{
	HOAlertView *amAlertView = [[HOAlertView alloc] initWithTitle:NSLocalizedString(@"您确定此报修单未完成吗?",  @"您确定此报修单未完成吗?")
														  message: nil
														 delegate: self
												cancelButtonTitle:NSLocalizedString(@"关闭", @"关闭")
												otherButtonTitles:NSLocalizedString(@"确定", @"确定"), nil];
	amAlertView.tag = [kHO_DIALOG_Uncomplete integerValue];
	[amAlertView show];
	[amAlertView release];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	[super alertView:alertView clickedButtonAtIndex:buttonIndex];
	if(alertView.tag == [kHO_DIALOG_Uncomplete integerValue] && buttonIndex  == 1)
	{
		
		[self sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_FaultIncomplete,
									  kHO_FIELD_OrderId:[NSNumber numberWithInt:self.orderEntity.orderId],}];
	}
}

- (void)onKeyboardWillShow:(NSNotification *)notification
{
	[super onKeyboardWillShow:notification];
	[baseTableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
	[self hideKeyboard];
}

- (void)hideKeyboard
{
	[[commentsEditView getTextView] resignFirstResponder];
	[commentsEditView resignFirstResponder];
}

- (void)viewWillAppear:(BOOL)animated
{
	self.tabBarController.tabBar.hidden = YES;
	[super viewWillAppear:animated];
	[self setNavigationItemTitle:NSLocalizedString(@"确认完成(评价)", @"确认完成(评价)")];
	[baseTableview reloadData];
	isNeedRepair = self.orderEntity.isNeedRepair;
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
	[self hideKeyboard];
}

- (void)didClickFooterButton:(UIButton *)btn
{
	if(self.orderEntity.status == HO_REPORT_ORDER_CONFIRMED)
		return;
	NSString *content = [self getTrimingCharaFromTextView:[commentsEditView getTextView]];
	if(content == nil || content.length == 0)
		content = @"无";
	[self sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_ConfirmComplete,
								  kHO_FIELD_OrderId:[NSNumber numberWithInt:self.orderEntity.orderId],
								  kHO_FIELD_Content:content,
								  kHO_FIELD_Score:[NSNumber numberWithInteger:ratingBarView.starNumber],
								  @"IsReSubmit":[NSNumber numberWithInt:isNeedRepair]
								  }];
}

#pragma mark - -- UITableViewDelegate/UITableViewDataResource implement methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if(indexPath.section == 0)
	{
		return 76;
	}
	else if(indexPath.section == 1)
	{
		return 180;
	}
	else
	{
		return 140;
	}
    return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}


- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	if(section == 0)
		return [HOUtils defaultOnePixelConversion];
    return SECTION_PADDING / 2;
}


#pragma mark

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	CGFloat cellHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];

	if(indexPath.section == 0)
	{
		
		static NSString *AMBaseTableViewCellIdentifier = @"HOConfirmTableViewCell";
		UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:AMBaseTableViewCellIdentifier];
		if(cell == nil)
		{
			cell = [[[UITableViewCell alloc]
					 initWithStyle:UITableViewCellStyleDefault
					 reuseIdentifier: AMBaseTableViewCellIdentifier] autorelease];
		}
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		UIImageView *headerImgView = (UIImageView *)[cell viewWithTag:13];
		if(headerImgView == nil)
		{
			UIImage *image = [UIImage imageNamed:@"chakanzhuangtai_touxiang"];
			headerImgView = [[[UIImageView alloc]
							  initWithFrame:CGRectMake(HO_HORIZONAL_PADDING,
													   (cellHeight - 58) / 2,
													   58,
													   58)] autorelease];
			headerImgView.tag = 13;
			[headerImgView setImage:image];
			[cell.contentView addSubview:headerImgView];
			headerImgView.layer.borderWidth = [HOUtils defaultOnePixelConversion];
			[headerImgView.layer setMasksToBounds:YES];
			headerImgView.layer.borderColor = UIColorFromRGB(0xcdcdcd).CGColor;
			headerImgView.layer.cornerRadius = 58 / 2;
		}
		[headerImgView sd_setImageWithURL:[NSURL URLWithString:repairerEntity.headPic] placeholderImage:[UIImage imageNamed:@"morentu"]];
		
		UILabel *nameLbl = (UILabel *)[cell viewWithTag:15];
		if(nameLbl == nil)
		{
			nameLbl = [[[UILabel alloc]
						initWithFrame:CGRectMake(HO_HORIZONAL_PADDING + headerImgView.frame.size.width + HO_HORIZONAL_PADDING,
												 0,
												 tableView.frame.size.width - 60,
												 40)] autorelease];
			nameLbl.tag = 15;
			nameLbl.text = @"维修人：杜浦";
			nameLbl.font = [UIFont systemFontOfSize:15];
			nameLbl.textColor = TEXT_COLOR_666666;
			[cell.contentView addSubview:nameLbl];
		}
		nameLbl.text = [NSString stringWithFormat:@"%d-%@",repairerEntity.userId, [HOUtils getValideString:repairerEntity.userName]];
		
		UILabel *locationLbl = (UILabel *)[cell viewWithTag:116];
		if(locationLbl == nil)
		{
			locationLbl = [[[UILabel alloc]
							initWithFrame:CGRectMake(nameLbl.frame.origin.x,
													 20,
													 tableView.frame.size.width - 60,
													 40)] autorelease];
			locationLbl.tag = 116;
			locationLbl.text = @"东十六病区";
			locationLbl.font = [UIFont systemFontOfSize:13];
			locationLbl.textColor = TEXT_COLOR_666666;
			[cell.contentView addSubview:locationLbl];
		}
		locationLbl.text = [NSString stringWithFormat:@"%@%@", NSLocalizedString(@"科室：", @"科室："), [HOUtils getValideString:repairerEntity.depName]];
		
		
		
		
		RatingBar *ratingBar = (RatingBar *)[cell viewWithTag:117];
		if(ratingBar == nil)
		{
			ratingBar = [[[RatingBar alloc]
								initWithFrame:CGRectMake(nameLbl.frame.origin.x,
														 49,
														 90,
														 30)  isSmall:NO] autorelease];
			[cell.contentView addSubview:ratingBar];
			ratingBar.tag = 117;
		}
		ratingBar.starNumber = ((int)(repairerEntity.appraise + 1));
		return cell;
	}
	
	else if(indexPath.section == 1)
	{
		
		static NSString *AMBaseTableViewCellIdentifier = @"HOConfirmTableViewCell";
		UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:AMBaseTableViewCellIdentifier];
		if(cell == nil)
		{
			cell = [[[UITableViewCell alloc]
					 initWithStyle:UITableViewCellStyleDefault
					 reuseIdentifier: AMBaseTableViewCellIdentifier] autorelease];
		}
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		UIView *view= (UIView *)[cell viewWithTag:316];
		if(view == nil)
		{
			view = [[[UIView alloc]
					 initWithFrame:CGRectMake(0,
											  0,
											  tableView.frame.size.width,
											  cellHeight)] autorelease];
			view.tag = 316;
			
			UIView *lineView = [[[UIView alloc]
								 initWithFrame:CGRectMake(50,
														  33.5,
														  tableView.frame.size.width - 50 - 50,
														  1)] autorelease];
			[lineView setBackgroundColor:UIColorFromRGB(0xcccccc)];
			[view addSubview:lineView];
			
			UILabel *lbl = [[[UILabel alloc]
							 initWithFrame:CGRectMake(95,
													  33.5,
													  tableView.frame.size.width - 95,
													  22)] autorelease];
			lbl.text = NSLocalizedString(@"匿名评价", @"匿名评价");
			[lbl sizeToFit];
			[lbl setBackgroundColor:[UIColor whiteColor]];
			lbl.textAlignment = NSTextAlignmentCenter;
			lbl.frame = CGRectMake((baseTableview.frame.size.width - lbl.frame.size.width) / 2,
								   22.5,
								   lbl.frame.size.width,
								   22);
			lbl.textColor = TEXT_GRAY_DARK_b4b4b4;
			lbl.font = [UIFont systemFontOfSize:12];
			[lbl setBackgroundColor:UIColorFromRGB(0xf9f9f9)];
			
			[view addSubview:lbl];
			[view addSubview:ratingBarView];
			ratingBarView.frame = CGRectMake((view.frame.size.width - ratingBarView.frame.size.width) / 2,
											 ratingBarView.frame.origin.y,
											 ratingBarView.frame.size.width,
											 ratingBarView.frame.size.height);
			
			UILabel *lbl2 = [[[UILabel alloc]
							 initWithFrame:CGRectMake(0,
													  ratingBarView.frame.size.height + ratingBarView.frame.origin.y + HO_HORIZONAL_PADDING,
													  view.frame.size.width,
													  22)] autorelease];
			lbl2.text = NSLocalizedString(@"您的评价让我们做的更好", @"您的评价让我们做的更好");
			lbl2.textColor = UIColorFromRGB(0xfed340);
			lbl2.textAlignment = NSTextAlignmentCenter;
			lbl2.font = [UIFont systemFontOfSize:12];
			[view addSubview:lbl2];
			
			[cell.contentView addSubview:view];
		}
		return cell;
	}
	
	else if(indexPath.section == 2)
	{
		
		static NSString *AMBaseTableViewCellIdentifier = @"HOConfirmTableViewCell";
		UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:AMBaseTableViewCellIdentifier];
		if(cell == nil)
		{
			cell = [[[UITableViewCell alloc]
					 initWithStyle:UITableViewCellStyleDefault
					 reuseIdentifier: AMBaseTableViewCellIdentifier] autorelease];
		}
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		HOEditView *editView = (HOEditView *)[cell viewWithTag:214];
		if(editView == nil)
		{
			editView = commentsEditView;
			[cell.contentView addSubview:editView];
			editView.tag = 214;
		}
#if 0
		UIButton *checkBtn = (UIButton *)[cell viewWithTag:216];
		if(checkBtn == nil)
		{
			checkBtn = [[[UIButton alloc]
						initWithFrame:CGRectMake(HO_HORIZONAL_PADDING,
												 cellHeight - 40,
												 24,
												 24)] autorelease];
			[checkBtn setBackgroundImage:[UIImage imageNamed:@"IC_putongbaoxiu_kuang"] forState:UIControlStateNormal];
//			[checkBtn addTarget:self action:@selector(didClickCheckBtn:) forControlEvents:UIControlEventTouchUpInside];
			[cell.contentView addSubview:checkBtn];
		}
		if(self.orderEntity.isResubmit)
		{
			[checkBtn setBackgroundImage:[UIImage imageNamed:@"IC_putongbaoxiu_gou"] forState:UIControlStateNormal];
		}
		else
		{
			[checkBtn setBackgroundImage:[UIImage imageNamed:@"IC_putongbaoxiu_kuang"] forState:UIControlStateNormal];
		}
		
		UILabel *lbl = (UILabel *)[cell viewWithTag:110];
		if(lbl == nil)
		{
			lbl = [[[UILabel alloc]
							initWithFrame:CGRectMake(checkBtn.frame.origin.x + HO_HORIZONAL_PADDING + checkBtn.frame.size.width,
													 checkBtn.frame.origin.y + 1,
													 tableView.frame.size.width - 60,
													 22)] autorelease];
			lbl.tag = 110;
			lbl.text = @"是否返修";
			lbl.font = [UIFont systemFontOfSize:14];
			lbl.textColor = TEXT_COLOR_666666;
			[cell.contentView addSubview:lbl];
		}
#endif
		return cell;
		
	}
	return nil;
	
}

- (void)didClickCheckBtn:(id)sender
{
	isNeedRepair = ! isNeedRepair;
	[baseTableview reloadData];
}
#pragma mark -- tool
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
	NSLog(@"didReceiveMemoryWarning-----------self:%@", self);
}

- (void)dealloc
{
	[commentsEditView release];
	[ratingBarView release];
	[repairerEntity release];
	[super dealloc];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)didReceiveCommand:(NSString *)action data:(id)data
{
	if([action isEqualToString:kHO_CMD_ReceiveNotificationMessage])
	{
		NSDictionary *dic = [data objectForKey:kHO_FIELD_Extras];
		int type = [[dic valueForKey:kHO_FIELD_SendType] intValue];
		int orderId = [[dic valueForKey:kHO_FIELD_OrderId] intValue];
		if(type == HO_NC_TYPE_ORDER_ASSIGNED && orderId == self.orderEntity.orderId)
		{
			[self requestData];
		}
	}
}

- (void)requestDidSuccessWithResponse:(HOBaseResponseEntity *)response
{
	if([response isEqualAction:kHO_ACTION_ConfirmComplete])
	{
		self.view.userInteractionEnabled = NO;
		[self sendCommand:kHO_CMD_Report_Detail_Changed data:nil];
		[self sendCommand:kHO_CMD_Report_List_Changed data:nil];
		[self popupHintView:@"提交成功" inTime:1.5 needCallback:YES];
		self.orderEntity.status = HO_REPORT_ORDER_CONFIRMED;
		
	}
	else if([response isEqualAction:kHO_ACTION_GetRepairmanInfo])
	{
		[repairerEntity parseDic:response.dataNode];
		[baseTableview reloadData];
	}
	else if([response isEqualAction:kHO_ACTION_FaultIncomplete])
	{
		[self popupHintView:@"已修改状态为未完成" inTime:1.5 needCallback:YES];
		[self sendCommand:kHO_CMD_Report_Detail_Changed data:nil];
	}
	
}

- (void)hintDidHide
{
	self.view.userInteractionEnabled = YES;
	[self goBack];
}

@end
